package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.*;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 新增菜品
     *
     * @param dishDTO
     */
    @Transactional
    @Override
    public void save(@RequestBody DishDTO dishDTO) {
        //补全菜品的基本信息
        Dish dish = Dish.builder()
                .status(StatusConstant.DISABLE)//默认为禁用
                .build();
        BeanUtils.copyProperties(dishDTO, dish);

        //添加菜品的基本信息
        dishMapper.insert(dish);

        //添加菜品的口味信息
        List<DishFlavor> dishFlavors = dishDTO.getFlavors();
        saveDishFlavor(dish, dishFlavors);

        //删除缓存
        cleanCache("dishCache:" + dishDTO.getCategoryId() );
    }

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        //设置分页参数
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        //执行查询
        List<DishVO> dishList = dishMapper.page(dishPageQueryDTO);
        //封装结果并返回
        Page<DishVO> dishPage = (Page<DishVO>) dishList;
        return new PageResult(dishPage.getTotal(), dishPage.getResult());
    }

    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        //查询菜品基本信息
        Dish dish = dishMapper.getById(id);

        //查询菜品口味信息
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);

        //封装结果并返回
        DishVO dishVO = DishVO.builder()
                .flavors(dishFlavors)
                .build();
        BeanUtils.copyProperties(dish, dishVO);
        return dishVO;
    }

    /**
     * 修改菜品
     *
     * @param dishDTO
     */
    @Transactional
    @Override
    public void update(DishDTO dishDTO) {
        //修改菜品的基本信息
        Dish dish = Dish.builder().build();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);

        //修改菜品的口味信息（先删，后加）
        //先删
        dishFlavorMapper.deleteByDishIds(Collections.singletonList(dish.getId()));
        //后加
        List<DishFlavor> dishFlavors = dishDTO.getFlavors();
        saveDishFlavor(dish, dishFlavors);

        //删除缓存
        cleanCache("dishCache:*");
    }

    private void cleanCache(String pattern) {
        Set<String> keys = redisTemplate.keys(pattern);
        if (CollectionUtils.isEmpty(keys)){
            return;
        }
        redisTemplate.delete(keys);
    }

    /**
     * 启售停售
     *
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        //如果是启售，直接修改状态即可
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);

        //如果是停售，那么关联该菜品的套餐也停售
        if (Objects.equals(status, StatusConstant.DISABLE)) {
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(Collections.singletonList(id));
            if (setmealIds.size() == 0) {//如果该菜品没有关联套餐，直接返回
                return;
            }
            //批量修改套餐状态为停售
            setmealIds.forEach(setmealId -> {
                Setmeal setmeal = Setmeal.builder()
                        .id(setmealId)
                        .status(StatusConstant.DISABLE)
                        .build();
                setmealMapper.update(setmeal);
            });

            //删除缓存
            cleanCache("dishCache:*");
        }
    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> getByCategoryId(Long categoryId) {
        return dishMapper.getByCategoryId(categoryId);
    }

    /**
     * 删除菜品
     *
     * @param ids
     */
    @Override
    @Transactional
    public void delete(List<Long> ids) {
        //启售中的菜品不允许删除
        Long count = dishMapper.countStatusByIds(ids, StatusConstant.ENABLE);
        if (count > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }

        //关联套餐的菜品不能删除
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmealIds.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //删除菜品的基本信息
        dishMapper.deleteByIds(ids);

        //删除菜品的口味信息
        dishFlavorMapper.deleteByDishIds(ids);

        //删除缓存
        cleanCache("dishCache:*");
    }

    /**
     * 根据分类id查询菜品信息和口味信息
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> getDishesByCategoryId(Long categoryId) {
        //判断缓存中是否有数据
        List<DishVO> data = (List<DishVO>) redisTemplate.opsForValue().get("dishCache:" + categoryId);
        if (!CollectionUtils.isEmpty(data)) {
            //有数据
            log.info("命中了缓存...");
            return data;
        }

        //如果缓存中没有数据
        List<DishVO> dishVOList = new ArrayList<>();
        //查询菜品的基本信息
        List<Dish> dishList = dishMapper.getByCategoryId(categoryId);
        dishList.forEach(dish -> {
            //查询菜品的口味信息
            List<DishFlavor> dishFlavorList = dishFlavorMapper.getByDishId(dish.getId());
            DishVO dishVO = DishVO.builder()
                    .flavors(dishFlavorList)
                    .build();
            BeanUtils.copyProperties(dish, dishVO);
            dishVOList.add(dishVO);
        });
        //则将数据将入缓存
        redisTemplate.opsForValue().set("dishCache:" + categoryId, dishVOList);
        return dishVOList;
    }


    /**
     * 添加菜品口味信息
     *
     * @param dish
     * @param dishFlavors
     */
    private void saveDishFlavor(Dish dish, List<DishFlavor> dishFlavors) {
        if (dishFlavors == null || dishFlavors.size() == 0 || dish == null) {
            return;
        }
        //遍历添加
        dishFlavors.forEach(dishFlavor -> {
            dishFlavor.setDishId(dish.getId());
        });
        //批量添加
        dishFlavorMapper.insertBatch(dishFlavors);
    }
}
